package com.verbetia.musictrends.service;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.queryParser.ParseException;

import com.verbetia.mbrainz.search.ResultItem;
import com.verbetia.mbrainz.search.TrackSearch;
import com.verbetia.musictrends.persistence.hsqldb.MusicsPersMngr;
import com.verbetia.musictrends.persistence.hsqldb.UsersPersMngr;



public class SendMusicService extends HttpServlet {

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{		
		String username = request.getParameter("user");
		String password = request.getParameter("pass");
		
		String musicdata = request.getParameter("song");
		
		int userid = -1;
		
		userid = authenticate(username, password);
				
  		if  (userid<0)
			return;
		
		
		ResultItem r = this.searchMetadata(musicdata);
		
		
		MusicsPersMngr music = new MusicsPersMngr();
		
		try {
			music.createInstance(Integer.toString(userid), 
								 musicdata, 
								 r.getTitle(), 
								 r.getArtist(), 
								 r.getAlbum(), 
								 r.getAsin());
		} 
		catch (SQLException sqle)
		{
			System.out.println(sqle);
		}
		
		
		
	}


	protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException 
	{
	}
	
	
	public ResultItem searchMetadata(String data)
	{
		ArrayList<ResultItem> results = null;
		
		if (data!=null || !data.equals(""))
		{
			try {
				results = TrackSearch.getInstance().searchTrack(normalizeData(data));
				
			} catch (IOException ioe)
			{
				System.out.println(ioe);
			} catch (ParseException pe)
			{
				System.out.println(pe);
			}
		}

		return results.get(0);
		
	}
	
	public String normalizeData(String data)
	{
		return data.replaceAll("-", "");
		
	}
	
	
	public int authenticate(String username, String password)
	{
		UsersPersMngr users = new UsersPersMngr();
		int userid=UsersPersMngr.USER_NOT_EXSIST;
		
		try {
			userid = users.authenticateUser(username, password);
		} catch (SQLException e)
		{
			System.out.println(e);			
		}
		
		return userid;
		
	}
	
	
	
	

}
